package com.xyy.saas.payment.adpater.jd.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.BaseNCodec;

import java.io.UnsupportedEncodingException;

/**
 * 编码工具类.
 */
public class JDCodecUtils {
    private static final String[] hexStrings;

    static {
        hexStrings = new String[256];
        for (int i = 0; i < 256; i++) {
            StringBuilder d = new StringBuilder(2);
            char ch = Character.forDigit(((byte) i >> 4) & 0x0F, 16);
            d.append(Character.toUpperCase(ch));
            ch = Character.forDigit((byte) i & 0x0F, 16);
            d.append(Character.toUpperCase(ch));
            hexStrings[i] = d.toString();
        }
    }

    /**
     * 对数据进行BASE64解码，默认是UTF8编码。
     *
     * @param base64Data Base64数据
     * @param oneLine    是否是一行
     * @return
     */
    public static String decodeBase64(String base64Data, boolean oneLine) throws UnsupportedEncodingException {
        return decodeBase64(base64Data, "UTF-8", false, oneLine);
    }

    /**
     * 对数据进行BASE64解码
     *
     * @param base64Data Base64数据
     * @param charset    解码的编码格式
     * @param urlSafe    是否是URL安全的，如果为true，则将会被URL编码的'+', '/'转成'-', '_'
     * @param oneLine    是否是一行
     * @return 解码后数据
     */
    public static String decodeBase64(String base64Data, String charset, boolean urlSafe, boolean oneLine) throws UnsupportedEncodingException {
        Base64 base64 = oneLine ?
                new Base64(BaseNCodec.MIME_CHUNK_SIZE, null, urlSafe) : new Base64(urlSafe);
        byte[] binaryData = base64.decode(base64Data);
        return new String(binaryData, charset);
    }




}
